package org.dfg.corejava.jdk6.stax;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.Reader;
import java.util.Iterator;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import javax.xml.stream.events.Attribute;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

public class MaintTest {

	public static void main(String[] a) throws FileNotFoundException, XMLStreamException {
		read();
		//write();
	}

	private static void write() throws FileNotFoundException, XMLStreamException {
		XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
		XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(new FileOutputStream(
				"C:/output.xml"));

		// 写入默认的 XML 声明到xml文档
		xmlw.writeStartDocument();
		xmlw.writeCharacters("\n");
		// 写入注释到xml文档
		xmlw.writeComment("testing comment");
		xmlw.writeCharacters("\n");
		// 写入一个catalogs根元素
		xmlw.writeStartElement("catalogs");
		xmlw.writeNamespace("myNS", "http://blog.csdn.net/Chinajash");
		xmlw.writeAttribute("owner", "Chinajash");
		xmlw.writeCharacters("\n");
		// 写入子元素catalog
		xmlw.writeStartElement("http://blog.csdn.net/Chinajash", "catalog");
		xmlw.writeAttribute("id", "007");
		xmlw.writeCharacters("Apparel");
		// 写入catalog元素的结束标签
		xmlw.writeEndElement();
		// 写入catalogs元素的结束标签
		xmlw.writeEndElement();
		// 结束 XML 文档
		xmlw.writeEndDocument();
		xmlw.close();
	}

	public static void read() throws FileNotFoundException, XMLStreamException {
		Reader in = new FileReader(new File("C:/output.xml"));

		XMLInputFactory factory = XMLInputFactory.newFactory();
		XMLEventReader reader = factory.createXMLEventReader(in);

		while (reader.hasNext()) {
			XMLEvent e = reader.nextEvent();
			System.out.print(e.isStartElement() + "-");
			if (e.isStartElement()) {
				StartElement ee = e.asStartElement();
				System.out.print(ee.getName() + "-");
				Iterator<Attribute> i = ee.getAttributes();
				while (i.hasNext()) {
					Attribute a = i.next();
					System.out.print(a.getName() + "=" + a.getValue());
				}
			}
			if (e.isCharacters()) {
				System.out.print(e.asCharacters().getData());
			}

			System.out.println();
		}
	}
}
